package com.ego.auth.properties;

import com.ego.auth.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@Slf4j
@Data
@ConfigurationProperties(prefix = "ego.jwt")
public class JwtProperties {

    private String pubKeyPath;
    private String priKeyPath;
    private String cookieName;
    private Integer expireMinutes;
    private String secret;
    private PrivateKey privateKey;
    private PublicKey publicKey;
    private Integer maxAge;

    //构造器->set->init->destroy

    public JwtProperties() {

    }

    /**
     * 当属性注入后才执行得方法
     * @throws Exception
     */
    @PostConstruct
    public void init() throws Exception {
        try {
            //检查私钥是否存在
            File priKeyFile = new File(priKeyPath);
            File pubKeyFile = new File(pubKeyPath);
            if (!priKeyFile.exists() || !pubKeyFile.exists()) {
                RsaUtils.generateKey(pubKeyPath,priKeyPath,secret);
            }
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
        } catch (Exception e) {
            log.error("加载私/公钥异常",e);
        }
    }
}
